package dkbta.server.util.query;

import java.util.Hashtable;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.log4j.Logger;

import dkbta.Config;
import dkbta.server.domain.cu.CUStub;


/**
 * Synchronized table
 * 
 * @author Arkady Mishiev
 *
 */
public class QueriesTable {
	private Hashtable<String,Query> m_table;
	private LinkedBlockingQueue<Results> m_resultsOutbox;
	private static Logger s_logger;
	
	public QueriesTable(LinkedBlockingQueue<Results> resultsOutbox){
		m_resultsOutbox = resultsOutbox;
		m_table = new Hashtable<String, Query>();
		s_logger = Logger.getLogger(QueriesTable.class);
	}
	
	public synchronized void addQuery(Query query){
		m_table.put(query.getId(), query);
	}

	public synchronized void addResults(String queryId, String results, String stubId){
		Query query = m_table.get(queryId);
		if(query == null){
			s_logger.warn("Discarding results of " + stubId + ". Some Unit reported Failure");
			return;
		}
		Results totalResults = query.addResults(results,stubId);
		/* if it was last results to submit */
		if(totalResults != null){
			try {
				m_resultsOutbox.put(totalResults);
				/* remove irrelevant query */
				m_table.remove(queryId);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				s_logger.warn("Failed while inserting results into outbox!!!");
			}
		}
		/* else do nothing */
	}

	public synchronized void reportUnitsFailure(String queryId, String stubId) {
		Query query = m_table.get(queryId);
		if(query != null){
			Results totalResults = new Results(queryId, 
				Config.FAILURE_PREFIX +	"Units Failure (" + stubId + ")", 
				query.getClientId());
			try {
				m_resultsOutbox.put(totalResults);
			} catch (InterruptedException e) {
				s_logger.warn("Failed while inserting Failure results into outbox!!!");
			}
			/* remove irrelevant query */
			m_table.remove(queryId);			
		}
		else{
			s_logger.warn("Discarding Failure of " + stubId + 
					". Some Unit already reported Failure");
		}
		/* else do nothing. Another Unit already reported Failure*/
	}
	
}
